import React, { useState, useEffect, useRef, useCallback } from 'react';

// 图片项接口
interface ImageItem {
    id: number;
    src: string;
    width: number;
    height: number;
    alt?: string;
}

// 组件属性接口
interface WaterfallGalleryProps {
    images: ImageItem[];
    columnMinWidth?: number;
    gap?: number;
}

// 瀑布流图片布局组件
const WaterfallGallery: React.FC<WaterfallGalleryProps> = ({
    images,
    columnMinWidth = 250,
    gap = 16,
}) => {
    const containerRef = useRef<HTMLDivElement>(null);
    const [columns, setColumns] = useState<number[]>([]);
    const [columnCount, setColumnCount] = useState(0);
    const [loadedImages, setLoadedImages] = useState<Set<number>>(new Set());

    // 计算列数和初始化列高度
    const calculateColumns = useCallback(() => {
        if (!containerRef.current) return;

        const containerWidth = containerRef.current.clientWidth;
        const newColumnCount = Math.max(
            1,
            Math.floor((containerWidth + gap) / (columnMinWidth + gap))
        );

        if (newColumnCount !== columnCount) {
            setColumnCount(newColumnCount);
            setColumns(new Array(newColumnCount).fill(0));
            setLoadedImages(new Set()); // 重置已加载图片状态
        }
    }, [columnCount, columnMinWidth, gap]);

    // 处理图片加载，更新列高度
    const handleImageLoad = useCallback((id: number, columnIndex: number, height: number) => {
        setColumns(prevColumns => {
            // 更新该列的高度
            const newColumns = [...prevColumns];
            newColumns[columnIndex] += height + gap;
            return newColumns;
        });

        // 记录已加载的图片
        setLoadedImages(prev => new Set([...prev, id]));
    }, [gap]);

    // 初始化和窗口大小变化时重新计算列数
    useEffect(() => {
        calculateColumns();

        const handleResize = () => {
            calculateColumns();
        };

        window.addEventListener('resize', handleResize);
        return () => window.removeEventListener('resize', handleResize);
    }, [calculateColumns]);

    return (
        <div
            ref={containerRef}
            style={{
                display: 'flex',
                flexDirection: 'row',
                gap,
                margin: '0 auto',
                width: '100%',
                maxWidth: '1350px',
                marginTop:'30px'
            }}
        >
            {Array.from({ length: columnCount }, (_, columnIndex) => (
                <div
                    key={columnIndex}
                    style={{
                        display: 'flex',
                        flexDirection: 'column',
                        gap,
                        flex: 1,
                    }}
                >
                    {images
                        .filter((_, index) => index % columnCount === columnIndex)
                        .map((image, imageIndex) => {
                            // 计算图片的实际高度
                            const aspectRatio = image.height / image.width;
                            const imageWidth = `calc((100% - ${gap * (columnCount - 1)}px) / ${columnCount})`;
                            const imageHeight = `calc(${imageWidth} * ${aspectRatio})`;

                            return (
                                <div
                                    key={image.id}
                                    style={{
                                        position: 'relative',
                                        width: '100%',
                                        paddingBottom: `${aspectRatio * 100}%`, // 保持图片比例的占位
                                        opacity: loadedImages.has(image.id) ? 1 : 0,
                                        transition: 'opacity 0.3s ease',
                                    }}
                                >
                                    <img
                                        src={image.src}
                                        alt={image.alt || `Image ${image.id}`}
                                        style={{
                                            position: 'absolute',
                                            top: 0,
                                            left: 0,
                                            width: '100%',
                                            height: '100%',
                                            borderRadius: '8px',
                                            boxShadow: '0 4px 6px rgba(0,0,0,0.1)',
                                            objectFit: 'cover',
                                        }}
                                        onLoad={() => handleImageLoad(image.id, columnIndex, parseFloat(imageHeight))}
                                        loading="lazy"
                                    />
                                </div>
                            );
                        })}
                </div>
            ))}
        </div>
    );
};

export default WaterfallGallery;  